import React from "react";
import { Menu } from "antd";
import type { MenuProps } from "antd";
import { getInstitutesInfo } from "@/apis";
import type { Institute, HandlerFindMajorType } from "@/types";
import { useEffect, useState } from "react";
import style from "./index.module.less";

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: "group"
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}

const SideBar: React.FC<{
  findMajorBySideBar: HandlerFindMajorType;
}> = (props: { findMajorBySideBar: HandlerFindMajorType }) => {
  const [institute, setInstitute] = useState<Institute>({ instituteInfo: [] });
  useEffect(() => {
    getInstitutesInfo()
      .then((res) => {
        setInstitute(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  }, []);
  const onClickMenuItem: MenuProps["onClick"] = (e) => {
    console.log("find ", e);
    props.findMajorBySideBar(e.key);
    // 查询这个专业
  };

  const instituteInfoItems: MenuProps["items"] = [
    ...institute.instituteInfo.map((item) => {
      return getItem(
        <p className={style.sideBarTitle}>{item.instituteName}</p>,
        item.instituteName,
        null,
        [
          ...item.majorList.map((major) => {
            return getItem(major.majorName, major.value as string);
          }),
        ]
      );
    }),
  ];

  return (
    <>
      <div>
        <Menu
          className={style.menuItems}
          onClick={onClickMenuItem}
          style={{ width: 256 }}
          defaultSelectedKeys={[]}
          defaultOpenKeys={[]}
          mode="inline"
          items={instituteInfoItems}
        />
      </div>
    </>
  );
};
export default SideBar;
